package com.gzist.security4.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzist.security4.domain.Role;
import com.gzist.security4.domain.User;
import com.gzist.security4.domain.dto.LoginParams;
import com.gzist.security4.service.UserService;
import com.gzist.security4.mapper.UserMapper;
import com.gzist.security4.utils.JWTUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 黄泽建
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-05-14 00:43:40
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private AuthenticationManager manager;

    @Override
    public String login(LoginParams loginParams) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginParams.getUsername(), loginParams.getPassword());
        Authentication authentication = null;
        try {
            //登录成功后将其用户信息取出存进authentication中
            authentication = manager.authenticate(authenticationToken);
        } catch (AuthenticationException e) {
            //当系统捕捉到错误的时候就
            e.printStackTrace();
            throw new BadCredentialsException("账号或者密码错误！");
        }
        //拿到用户信息后将其与权限信息一齐封装存进jwt中进行返回
        Map<String,Object> claims = new HashMap<>();
        User user = (User) authentication.getPrincipal();
        // 对于登录业务这只需要将用户信息存进authentication即可，无需存进SecurityContextHolder
        claims.put("id",user.getId());
        claims.put("username",user.getUsername());
        claims.put("nickname",user.getNickname());
        claims.put("perms",user.getPerms());
        return JWTUtils.createJwt(claims);
    }

    @Override
    public List<Role> getAllRoles(Long id) {
        return userMapper.getAllRoles(id);
    }

}


